#include"Polygons.h"

/////////////////
//include
/////////////////
#include"Octree.h"
#include"DeviceContext.h"
#include"PrimitiveDrawer.h"
#include"Line.h"
#include"CppHeader.h"
/////////////////
//prottype
/////////////////

/////////////////
//const
/////////////////


Polygons::Polygons(Array<Triangle*> polygons)
{
	this->polygons = polygons;
	spheres = Array<Sphere>(polygons.GetSize());
	for(int i = 0;i<polygons.GetSize();i++)
	{
		spheres[i] = polygons[i]->GetSphere();
	}
}
Polygons::~Polygons()
{
	if(polygons.GetReference() == 1)
	{
		for(int i = 0;i<polygons.GetSize();i++)
		{
			delete polygons[i];
		}
	}
}
TriCollInfo Polygons::GetCollisionLine(const Vector3D& start,const Vector3D& end,const Vector3D& offset_pos,const Matrix& rot_mat,float size)
{
	float tmp_length = FLT_MAX;
	TriCollInfo info ;
	TriCollInfo tmp_info ;
	Line line = Line(start,end);
	//Clock c = Clock();
	//c.Start();
	for(int i = 0;i<polygons.GetSize();i++)
	{
		//if(!spheres[i].Collision(line))

		polygons[i]->CollisionLine(tmp_info,start,end,offset_pos,rot_mat,size);

		if(tmp_info.is_collision)
		{
			if(tmp_length > (tmp_info.pos - start).LengthSquare())
			{
				info = tmp_info;
				tmp_length = (tmp_info.pos - start).LengthSquare();
			}

		}

	}
	//c.End("Polygons");
	return info;
}
CollInfo Polygons::GetTriSpheres(Sphere* sphere)
{
	CollInfo info = CollInfo();
	info.is_collision = false;
	float tmp_min_length = FLT_MAX;
	for(int i = 0;i<spheres.GetSize();i++)
	{
		if(sphere->Collision(spheres[i]))
		{
			float tmp_length = (spheres[i].GetPos() - sphere->GetPos()).Length();
			if(tmp_min_length > tmp_length)
			{
				tmp_min_length = tmp_length;
				info.is_collision = true;
				info.pos = spheres[i].GetPos();
			}
		}
	}

	return info;
}
void Polygons::Draw(DeviceContext* device_context,Vector3D offset_pos)
{
	for(int i = 0;i<polygons.GetSize();i++)
	{
		PrimitiveDrawer::DrawTriangle(device_context,offset_pos,polygons[i]->vertex[0],polygons[i]->vertex[1],polygons[i]->vertex[2]);
	}
}